// pages/dishes/dishes.js
const app = getApp()
const auth = require('../../utils/auth')

Page({
  data: {
    searchKey: '',
    category: 'all',
    categories: [
      { id: 'all', name: '全部' },
      { id: '家常菜', name: '家常菜' },
      { id: '汤羹', name: '汤羹' },
      { id: '主食', name: '主食' },
      { id: '西餐', name: '西餐' }
    ],
    dishList: [],
    filteredList: [],
    loading: false,
    isAuthenticated: false,
    currentUser: null
  },

  onLoad() {
    this.checkAuthentication()
    this.loadDishes()
  },

  onShow() {
    this.checkAuthentication()
    this.loadDishes()
  },

  // 检查认证状态
  checkAuthentication() {
    // 首先检查是否已经有认证状态
    const currentUser = auth.getCurrentUser()
    if (currentUser) {
      this.setData({
        isAuthenticated: true,
        currentUser: currentUser
      })
      return
    }
    
    // 如果没有认证状态，重新检查
    auth.checkAuthentication()
      .then(user => {
        auth.setCurrentUser(user)
        this.setData({
          isAuthenticated: true,
          currentUser: user
        })
      })
      .catch(err => {
        this.setData({
          isAuthenticated: false,
          currentUser: null
        })
        wx.showModal({
          title: '需要身份验证',
          content: '使用菜品管理功能需要先进行身份验证',
          showCancel: false,
          success: () => {
            wx.switchTab({
              url: '/pages/home/home'
            })
          }
        })
      })
  },

  // 加载菜品列表
  loadDishes() {
    if (!this.data.isAuthenticated) {
      this.setData({
        dishList: [],
        filteredList: [],
        loading: false
      })
      return
    }
    
    this.setData({ loading: true })
    
    const db = wx.cloud.database()
    db.collection('dishes')
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        this.setData({
          dishList: res.data,
          loading: false
        })
        this.filterDishes()
      })
      .catch(err => {
        console.error('加载菜品失败：', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      })
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKey: e.detail.value
    })
    this.filterDishes()
  },

  // 选择分类
  onCategorySelect(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ category })
    this.filterDishes()
  },

  // 筛选菜品
  filterDishes() {
    let { dishList, searchKey, category } = this.data
    let filteredList = [...dishList]
    
    // 按分类筛选
    if (category !== 'all') {
      filteredList = filteredList.filter(item => item.category === category)
    }
    
    // 按搜索关键词筛选
    if (searchKey) {
      filteredList = filteredList.filter(item => 
        item.name.includes(searchKey) || 
        item.desc.includes(searchKey)
      )
    }
    
    this.setData({ filteredList })
  },

  // 跳转到添加菜品
  navigateToAdd() {
    wx.navigateTo({
      url: '/pages/addDish/addDish'
    })
  },

  // 编辑菜品
  onEdit(e) {
    const id = e.currentTarget.dataset.id
    const dish = this.data.filteredList.find(item => item._id === id)
    wx.navigateTo({
      url: '/pages/addDish/addDish?id=' + id
    })
  },

  // 删除菜品
  onDelete(e) {
    const id = e.currentTarget.dataset.id
    const dish = this.data.filteredList.find(item => item._id === id)
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除菜品"${dish.name}"吗？`,
      success: res => {
        if (res.confirm) {
          this.deleteDish(id)
        }
      }
    })
  },

  // 执行删除
  deleteDish(id) {
    const db = wx.cloud.database()
    db.collection('dishes')
      .doc(id)
      .remove()
      .then(() => {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.loadDishes()
      })
      .catch(err => {
        console.error('删除失败：', err)
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        })
      })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadDishes()
    wx.stopPullDownRefresh()
  },

  // 跳转到身份验证
  goToAuth() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  }
})